<template>
  <div class="clearfix">
    <a-upload
      :action="`${baseURL}uploadpic`"
      list-type="picture-card"
      :file-list="fileList"
      name="file"
      @preview="handlePreview"
      @change="handleChange"
    >
      <div v-if="fileList.length < maxNum">
        <i class="icon-21 iconfont"></i>
        <div class="ant-upload-text">上传图片</div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>
<script>
import { baseURL } from '@/config'
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

export default {
  props: {
    // 最大张传图片数量
    maxNum: {
      type: Number,
      default: 10,
    },
    hasAvatar: {
      type: String || Array,
    },
  },
  data() {
    return {
      previewVisible: false,
      // 预览图片
      previewImage: '',
      // 文件列表
      fileList: [],
      baseURL: baseURL,
    }
  },
  watch: {
    hasAvatar: {
      handler(newV, oldV) {
        console.log(newV)
        if (newV != '') {
          this.fileList = []
          this.fileList.push({
            uid: '-1',
            name: 'image.png',
            status: 'done',
            url: newV,
          })
        } else {
          this.fileList = []
        }
      },
      immediate: true,
    },
  },
  methods: {
    handleCancel() {
      this.previewVisible = false
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleChange({ fileList }) {
      console.log(fileList)
      // done 为上传成功状态
      if (fileList.length >= 1 && fileList[fileList.length - 1].status === 'done') {
        this.$message.success('上传成功')
        this.$emit('imags', fileList)
      }
      this.fileList = fileList
    },
  },
}
</script>
<style>
/* you can make up upload button and sample style by using stylesheets */
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
